<?php
/**
 * Created by PhpStorm.
 * User: yellow
 * Date: 2019/7/17
 * Time: 15:26
 */

namespace app\common\service\sms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use app\common\service\code\ErrorCode;

class AliyunSms
{
    private static $accessKeyId = 'LTAI7EjDYEEljbu7';
    private static $accessSecret = 'iaHezldXthyqgygK85tZ0ls9xxwD7Z';
    private static $signName = "旅游车";
    private static $smsType;
    private static $smsTemplate;
    private static $smsContent;

    public function __construct($smsType)
    {
        self::$smsType = $smsType;
        AlibabaCloud::accessKeyClient(self::$accessKeyId, self::$accessSecret)
            ->regionId('cn-hangzhou') // replace regionId as you need
            ->asDefaultClient();
    }

    public function sendSms($mobile, $param){
        $this->_getContent($param);
        try{
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $mobile,
                        'SignName' => self::$signName,
                        'TemplateCode' => self::$smsTemplate,
                        'TemplateParam' => self::$smsContent,
                    ],
                ])
                ->request();
            $result = json_decode($result, true);
            if ($result['Code'] === 'OK'){
                //发送成功
                return ajaxArr(ErrorCode::$SUCCESS, '发送短信成功');
            } else{
                return ajaxArr($result['Code'], $result['Message']);
            }
        } catch (ClientException $e) {
            return ajaxArr(ErrorCode::$EXCEPTION, $e->getErrorMessage());
        } catch (ServerException $e) {
            return ajaxArr(ErrorCode::$EXCEPTION, $e->getErrorMessage());
        }

    }

    /**
     * 获取短信内容
     * @param $param
     */
    private function _getContent($param){
        switch (self::$smsType){
            case 1:
                //验证码短信
                self::$smsTemplate = "SMS_109570056";
                self::$smsContent = json_encode($param);
                break;
            default:
                break;
        }
    }

}